<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\index\controller;
use app\common\controller\Home;
use app\index\config;

class Index extends Home {
	//网站首页
	public function index() {
	    //0可用  1禁用
        $model_list = db('member')->where(array('show' => '0'))->limit(0,9)->select();
        $this->assign('model_list', $model_list);
		return $this->fetch();
	}
	/*找回密码*/
    public function resetPassword(){
        if (IS_POST){
            $result = db('member')->where(array('uid' => $_POST['uid']))->find();
            if($result > 0){
                if($_POST['mbdaan'] == $result['mbdaan']){
                    $data = model('Member')->where('uid',$_POST['uid'])->update(['password' => md5($_POST['password'])]);
                    if($data > 0){
                        return $this->success('密码重置成功！', url('index/index/index'));
                    }else{
                        return $this->error('不得和原密码一致，请重新设置', '');
                    }
                }else{
                    return $this->error('密保错误', '');
                }
            }else{
                return $this->error('用户不存在', '');
            }
        } else {
            return $this->fetch();
        }
    }
    //个人详情页
    public function detail() {
        return $this->fetch();
    }
    //查看更多
    public function moreMember() {
        return $this->fetch();
    }
    //密码重置
    public function reset() {
        return $this->fetch();
    }
    //memDetail
    public function memDetail() {
        return $this->fetch();
    }
    /*用户登录*/
    public function login($username = '', $password = '', $verify = ''){
        if (IS_POST){
            if (!$username || !$password){
                return $this->error('用户名或者密码不能为空！', '');
            }
            //验证码验证
            //$this->checkVerify($verify);
            $user = model('User');
            $uid  = $user->login($username, $password,4);
            /*判断用户是否被禁用*/
            $show = model('Member')->where(array('uid'=>$uid))->find();
            if(1 == $show['show']){
                return $this->success('您已被系统禁用,请在右上角联系管理员！');
            }
            if ($uid > 0){
                $time = model('member')->where(array('uid'=>$uid))->find();
                if(date("d",$time['last_login_time']) == date("d",time())){
                    return $this->success('登录成功！', url('index/index/index'));
                }else{
                    model('member')->save(array('score'=>intval($time['score']+1)),array('uid'=>$uid));
                    return $this->success('登录成功+2分！', url('index/index/index'));
                }
            } else {
                switch ($uid){
                    case -1:$error = '用户不存在或被禁用！';
                        break; //系统级别禁用
                    case -2:$error = '密码错误！';
                        break;
                    default:$error = '未知错误！';
                        break; // 0-接口参数错误（调试阶段使用）
                }
                return $this->error($error, '');
            }
        } else {
            return $this->fetch();
        }
    }

    /*用户注册*/
    public function register($username = '', $password = '',$againPwd = ''){
        if (IS_POST){
            if($password == $againPwd){
                $data['username'] = $username;
                $data['password'] = md5($password);
                $uid = db('member')->insert($data);
                /*有bug---最后一条不一定是当前用户的id*/
                $yy = db('member')->getLastInsID();
                model('User')->login($yy, $password,4);
                if ($uid > 0){
                    return $this->success('请记下您的yy号:'.$yy, url('index/index/register02', array('panduan' => $yy)));
                } else {
                    return $this->error('注册失败', '');
                }
            }else{
                return $this->error('两次密码不一致', '');
            }
        }else{
            $user = model('User');
            $user->logout();
            return $this->fetch();
        }
    }
    /*意见*/
    public function yijian(){
        $uid = db('fankui')->insert($_POST);
        /*禁用被投诉的账号*/
        if ($uid > 0){
            return $this->success('提交成功！');
        } else {
            return $this->error('系统错误，请稍后重试！');
        }
    }
    /*投诉*/
    public function tousu(){
        $uid = db('tousu')->insert($_POST);
        if ($uid > 0){
            return $this->success('提交成功！');
        } else {
            return $this->error('系统错误，请稍后重试！');
        }
    }

    public function register02($panduan)
    {
        if (IS_POST){
            $array = ['uid','sex','hunfou','zinv','xueli','shouru','qq','mobile','shengao','mibao'];
            foreach ($_POST as $key=>$val){
                in_array($key, $array)? $_POST[$key] = intval($_POST[$key]):false;
            }
            $result = model('Member')->save($_POST, array('uid' => $_POST['uid']));
            if ($result > 0){
                return $this->success('操作成功！', url('index/index/index'));
            } else {
                return $this->error('您尚未变更信息！', url('index/index/index'));
            }
        } else{
            $list = [];
            if ('1' == $panduan){//编辑
                $list = model('Member')->selfDetail();
                $this->assign('bianji', true);
                $this->assign('list', $list);
                $this->assign('id',$_SESSION['index']['user_auth']['uid']);
            } else {//新增
                $this->assign('list', json_encode($list));
                $this->assign('id',$panduan);
            }
            return $this->fetch();
        }
    }

    /*public function memlist(){
        $order = "uid desc";
        $list  = model('Member')->order($order)->paginate(6);
        $data = array(
            'list' => $list,
            'page' => $list->render(),
        );
        $this->assign($data);
        return $this->fetch();
    }*/
    public function memlist(){
        return $this->fetch();
    }
    public function memshai($page = '6')
    {
        $array = [];$data['cur'] = $_POST['current']? $_POST['current']:'1';
        foreach($_POST as $key =>$val){
            33 == $val? false:$array[$key] = $val;
        }
        if(isset($array['height'])){
            $start = explode(',',$array['height']);
            unset($array['height'],$array['current']);
            $result = model('Member')->order("uid desc")->where('shengao','between',[$start[0],$start[1]])->where($array)->limit(($_POST['current']-1)*$page,$page)->select();
            $data['total'] = ceil(count(model('Member')->where('shengao','between',[$start[0],$start[1]])->order("uid desc")->where($array)->select())/$page);
        }else{
            unset($array['current']);
            $result = model('Member')->order("uid desc")->where($array)->limit(($_POST['current']-1)*$page,$page)->select();
            $data['total'] = ceil(count(model('Member')->order("uid desc")->where($array)->select())/$page);
        }
        $data['result'] = $result;
        return $data;
    }
    /**
     * 图片上传
     */
    public function imageUpload(){
        $base64_img = trim($_POST['passData']);
        $up_dir = './upload/';//存放在当前目录的upload文件夹下
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777);
        }
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('jpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.$_POST['type'].'_'.$_POST['number'].'.'.'png';
                if(file_exists($new_file) && file_exists($new_file))
                { //检查图片文件是否存在
                    unlink($new_file);
                }
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = substr(str_replace('../../..', '', $new_file),1);
                    model('Member')->save(array($_POST['type'] => $img_path), array('uid' => $_POST['number']));
                    return $this->success('上传成功！','',array('img_path'=>$img_path));
                }else{
                    return $this->error('上传失败，请重试...');
                }
            }else{
                //文件类型错误
                return $this->error('图片上传类型错误！');
            }
        }else{
            //文件错误
            return $this->error('文件错误！');
        }
    }
    /*loginOut退出*/
    public function loginOut(){
        $user = model('User');
        $user->logout();
        $this->redirect('index/index/index');
    }
    /*投诉+反馈*/
    public function fankui(){
        if (is_login()){
            return $this->fetch();
        }else{
            $this->redirect('index/index/login');
        }
    }
    /*试探积分是否够*/
    public function liwu(){
        if(is_login()){
            $result = model('Member')->where('uid',$_SESSION['index']['user_auth']['uid'])->find();
            $num = 0;
            foreach ($_POST['data'] as $key=>$val){
                $num = $num + $val['score'];
            }
            $score = $result['score'] - $num;
            if($score > 0){
                $jieguo = model('Member')->save(array('score' => $score), array('uid' => $_SESSION['index']['user_auth']['uid']));
                $liwu = model('Liwu')->save(array('liwu' => json_encode($_POST['data']),'fasong' => $_SESSION['index']['user_auth']['uid'],'jieshou' => $_POST['jieshou'],'shijian' => date('Y-m-d H:i:s', time())));
                return $jieguo && $liwu ? $this->success('礼物已发送！', url('index/Oneself/selfDetail')):$this->success('系统错误，请稍后重试！','');
            }else{
                return $this->success('sorry,积分不足');
            }
        }else{
            $this->redirect('index/index/login');
        }
    }
}
